package com.mszlu.msauth.admin.controller;

import com.mszlu.msauth.response.PageResult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OrganizationService {
    private final OrganizationConvert organizationConvert;
    @Autowired
    private OrganizationRepository organizationRepository;

    public PageResult<Organization> findByPage(OrganizationDTO org) {
        PageRequest pageRequest = PageRequest.of(org.getPage(), org.getPageSize());
        Page<Organization> all = organizationRepository.findAll(pageRequest);
        return PageResult.of(all, org.getPage(), org.getPageSize());
    }

    public List<OrganizationVO> listOrganization(OrganizationDTO org) {
        List<Organization> organizationList = organizationRepository.findAll(Sort.by(Sort.Order.asc("sort")));
        return toTreeList(0L, organizationList);
    }

    private List<OrganizationVO> toTreeList(Long parentId, List<Organization> all) {
        return all.stream().filter(organization -> organization.getParentId().equals(parentId)).map(organization -> {
//            OrganizationVO organizationVO = organizationConvert.toVO(organization);
            OrganizationVO organizationVO = new OrganizationVO();
            organizationVO.setChildren(toTreeList(organization.getId(), all));
            return organizationVO;
        }).collect(Collectors.toList());
    }
}